/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate;

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author craneleeon@gmail.com
 */
public class DeclareCacheHeaderFilter implements Filter {

    protected static final Log logger = LogFactory.getLog(DeclareCacheHeaderFilter.class);
    private String timeout = "0"; 
    
    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletResponse hres = (HttpServletResponse) response;
            hres.setHeader("Cache-Control", "max-age="+timeout);
            chain.doFilter(request, hres);

        } catch (Exception e) {
            logger.debug("Add Header Failed", e);
        }

        
    }

    /**
     * Destroy method for this filter 
     *
     */
    public void destroy() {
    }

    /**
     * Init method for this filter 
     *
     */
    public void init(FilterConfig filterConfig) {
        timeout = filterConfig.getInitParameter("timeout");
        if(timeout != null && !timeout.isEmpty()){
            try {
                Integer.parseInt(timeout);
            } catch (NumberFormatException numberFormatException) {
                timeout = "0";
            }
        }else{
            timeout = "0";
        }
    }

}
